package xin.yangshuai.kafka01.producer;

import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

public class CustomProducerCallbackPartitions {

    public static void main(String[] args) {

        String connectString = "192.168.145.132:9092,192.168.145.133:9092,192.168.145.134:9092";

        // 0 配置
        Properties properties = new Properties();
        // 连接集群
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, connectString);
        // 指定key和value的序列化类型
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());

        // 1 创建kafka生产者对象
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties);

        // 2 发送数据
        for (int i = 0; i < 5; i++) {
            // 带回调的异步发送
            // 不指定分区不设置key
            kafkaProducer.send(new ProducerRecord<>("first", "send message with callback-" + i
            // 指定分区
//            kafkaProducer.send(new ProducerRecord<>("first", 1, "", "send message set partition with callback-" + i
            // 设置key
//            kafkaProducer.send(new ProducerRecord<>("first", "a", "send message set key with callback-" + i
            ), new Callback() {
                @Override
                public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                    if (e == null) {
                        System.out.println("主题：" + recordMetadata.topic() + " 分区：" + recordMetadata.partition());
                    }
                }
            });
        }

        // 3 关闭资源
        kafkaProducer.close();
    }
}
